<?php
namespace DRY\Module;

/**
 * DonReY Framework 2012 :: Document access and assembly - Useful in building a CMS
 * A document is usually a string in HTML format, but it can be something else as well.
 * Uses various Models to represent documents ( stored as files, or inside a database, or a combination of template/data used to generate a document )
 * Each model implements CRUD on the document.
 *
 * @author Wavetrex <wavetrex@gmail.com>
 * @link http://www.donrey.net/Documentation/Structure/Modules/document.html
 * @license [GPL v3] http://www.gnu.org/licenses/gpl-3.0.html
 * @version 1.0.dev
 * @package DonReY
 * @subpackage Module.Document
 */
class Document extends base
{
	// Autoloader configuration
	const
		Autoload_Directory = 'document',
		Autoload_Prefix = 'DRY\Document\Model',
		Autoload_Suffix = 'model'
		;

	/**
	 * Instances a "Document Model" object
	 * @param string $reference Model reference inside the module's configuration
	 * @param mixed $id Identifier for this document
	 * @param mixed $params Extra parameters for the Model
	 * @return \DRY\Document\base
	 */
	public function factory_Model($reference, $id = null, $params = null)
	{
		$model_type = (string)$this-> CFG-> models-> {$reference}['model'];
		if(empty($model_type))
			return null; // when no valid type found in CFG
		$content_class = self::Autoload_Prefix.'_'.$model_type;
		return new $content_class($this, $this-> CFG-> models-> $reference, $id, $params);
	}

	/**
	 * Searches all document attributes for a certain value, and returns the Model object which contains that attribute
	 * @param string $reference
	 * @param string $attr
	 * @param mixed $value
	 * @return DRY\Document\Model_base
	 */
	public function search_By_Attribute($reference, $attr, $value)
	{
		$model_type = (string)$this-> CFG-> models-> {$reference}['model'];
		if(empty($model_type))
			return null; // when no valid type found in CFG

		$content_class = self::Autoload_Prefix.'_'.$model_type;

		return $content_class::search_Attribute($this, $this-> CFG-> models-> $reference, $attr, $value);
	}


}

namespace DRY\Document;

/**
 * A Document model must implement these methods
 *
 * @author Wavetrex <wavetrex@gmail.com>
 * @link http://www.donrey.net/Documentation/Structure/Modules/document.html
 * @license [GPL v3] http://www.gnu.org/licenses/gpl-3.0.html
 * @version 1.0.dev
 * @package DonReY
 * @subpackage Module.Document
 */
abstract class Model_base
{
	abstract function read();
	abstract function write($content = '');
	abstract function destroy();

	public function __toString()
	{
		return $this-> read();
	}
}